package com.tcxhb.job.core.schedule.workflow;

import com.tcxhb.job.dao.dataobject.JobInfoDO;
import com.tcxhb.job.dao.dataobject.JobInstanceDO;
import com.tcxhb.job.common.constants.BaseException;
import com.tcxhb.job.common.constants.enums.JobStatusEnum;
import com.tcxhb.job.common.model.MiscResult;
import com.tcxhb.job.core.entity.JobRunDTO;
import com.tcxhb.job.core.schedule.execute.JobRunContext;
import com.tcxhb.job.core.service.job.JobInfoService;
import com.tcxhb.job.core.service.job.JobInstanceService;
import com.tcxhb.job.core.utils.TraceUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * @Auther: tcxhb
 * @Date: 2023/11/12
 */
@Component
@Slf4j
public class JobCheckFlow implements FlowHandler<JobRunContext> {
    @Autowired
    private JobInfoService jobInfoService;
    @Autowired
    private JobInstanceService jobInstanceService;

    @Override
    public MiscResult handle(JobRunContext cxt) {
        JobRunDTO run = cxt.getReq();
        //查询任务信息
        String traceId = TraceUtils.buildTraceId(run.getJobId(), run.getScheduleTime(), 1);
        JobInfoDO jobDO = jobInfoService.queryById(run.getJobId());
        // 不是执行一次需要校验时间和任务
        if (!cxt.getReq().getRunOnce()) {
            //任务未启动
            if (!JobStatusEnum.start.eq(jobDO.getStatus())) {
                log.error("job-status-error,{}", traceId);
                throw new BaseException("1001", "任务非启动状态");
            }
            // 任务时间不对
            if (!jobDO.getNextTime().equals(run.getScheduleTime())) {
                log.error("job-scheduleTime-error,{},{}" + traceId, jobDO.getNextTime());
                throw new BaseException("1001", "任务执行时间不一致");
            }
        }
        // 任务重复提交
        JobInstanceDO exit = jobInstanceService.queryByTraceId(jobDO.getId(), traceId);
        if (exit != null) {
            log.error("job-repeat-run,{}", traceId);
            throw new BaseException("1001", "任务重复提交");
        }
        //任务信息
        cxt.setJobDO(jobDO);
        cxt.setAppName(jobDO.getAppName());
        cxt.setRunStrategy(jobDO.getRunStrategy());
        return MiscResult.suc();
    }
}
